<template>
	<view class="details-page">
		<!-- 地图（保持不变） -->
		<view class="map-container">
			<mapVue :selectMarker="selectMarker" :latitude="userDetails.latitude" :longitude="userDetails.longitude"
				:isMappage="isMappage"></mapVue>
		</view>

		<!-- 内容容器 -->
		<view class="content-wrapper">
			<!-- 基本信息卡片（保持不变） -->
			<view class="info-card">
				<view class="card-header">
					<text class="card-title">基本信息</text>
				</view>

				<view class="device-info">
					<view class="device-name">{{ userDetails.deviceName || '未知设备' }}</view>

					<view class="info-grid">
						<view class="info-item">
							<text class="info-label">所属用户:</text>
							<text class="info-value">{{ userDetails.ownerName || '暂无' }}</text>
						</view>
						<view class="info-item">
							<text class="info-label">设备编号:</text>
							<text class="info-value">{{ userDetails.id || '暂无' }}</text>
						</view>
						<view class="info-item">
							<text class="info-label">IMEI:</text>
							<text class="info-value">{{ userDetails.imei || '暂无' }}</text>
						</view>
						<view class="info-item">
							<text class="info-label">所属组织:</text>
							<text class="info-value">{{ userDetails.projectName || '暂无' }}</text>
						</view>
					</view>

					<view class="device-status" :class="userDetails.online ? 'status-online' : 'status-offline'">
						{{ userDetails.online ? '在线' : '休眠' }}
					</view>
				</view>
			</view>

			<!-- Tab切换区域（保持不变） -->
			<view class="tab-container">
				<view class="tab-wrapper">
					<view class="tab-item" :class="{ 'active': current === 0 }" @click="current = 0">
						<text class="tab-text">实时数据</text>
					</view>
					<view class="tab-item" :class="{ 'active': current === 1 }" @click="changeLastData">
						<text class="tab-text">设备历史记录</text>
					</view>
				</view>
			</view>

			<!-- 内容区域 -->
			<view class="content-area">
				<!-- 实时数据（保持不变） -->
				<view v-if="current === 0" class="realtime-container">
					<view class="data-cards">
						<view class="data-card">
							<view class="data-icon">📊</view>
							<view class="data-title">瞬时流量</view>
							<view class="data-value">
								{{ liveDate['瞬时流量']?.value || 0 }}{{ liveDate['瞬时流量']?.unit || '' }}
							</view>
						</view>

						<view class="data-card">
							<view class="data-icon">📈</view>
							<view class="data-title">正向累积</view>
							<view class="data-value">
								{{ liveDate['正向累积']?.value || 0 }}{{ liveDate['正向累积']?.unit || '' }}
							</view>
						</view>

						<view class="data-card">
							<view class="data-icon">🎯</view>
							<view class="data-title">定量值</view>
							<view class="data-value">
								{{ liveDate['定量值']?.value || 0 }}{{ liveDate['定量值']?.unit || '' }}
							</view>
						</view>

						<view class="data-card">
							<view class="data-icon">⚙️</view>
							<view class="data-title">定量模式</view>
							<view class="data-value">
								{{ liveDate['定量模式']?.unit === 0 ? '自动' :
									liveDate['定量模式']?.unit === 1 ? '强制开' :
										'强制关' }}
							</view>
						</view>
					</view>
				</view>

				<!-- 历史记录（修改部分） -->
				<view v-if="current === 1" class="history-container">
					<scroll-view scroll-y="true" :show-scrollbar="false" class="history-scroll">
						<view class="date-picker" @click="calendarShow = true">
							<text class="date-text">{{ dateRange || '选择日期范围' }}</text>
							<text class="date-icon">▾</text>
						</view>

						<u-calendar :minDate="minDate" :maxDate="maxDate" :monthNum="24" :show="calendarShow"
							:mode="mode" @confirm="confirm" :readonly="false"
							@close="calendarShow = false"></u-calendar>

						<u-loading-icon v-if="isEnd" text="加载中" textSize="18"></u-loading-icon>

						<view v-else class="history-table">
							<!--  -->
							<u-table :data="tableData" :border="true" :stripe="true" :height="tableheight" emptyHeight="50">
								<u-table-column prop="name" label="日期" width="150">
									<template #default="{ row }">
										{{ formatDate(row.timestamp * 1000) }}
									</template>
								</u-table-column>
								<u-table-column prop="name" label="瞬时流量" width="120">
									<template #default="{ row }">
										{{ row.FS_d_1 || '0' }} m³/h
									</template>
								</u-table-column>
								<u-table-column prop="name" label="正向累积" width="120">
									<template #default="{ row }">
										{{ row.FS_d_2 || '0' }} m³
									</template>
								</u-table-column>
								<u-table-column prop="name" label="定量值" width="120">
									<template #default="{ row }">
										{{ row.FS_d_3 || '0' }} m³
									</template>
								</u-table-column>
								<u-table-column prop="name" label="定量模式" width="120">
									<template #default="{ row }">
										{{ row.FS_d_4 === 0 ? '自动' :
													row.FS_d_4 === 1 ? '强制开' : '强制关' }}
									</template>
								</u-table-column>
								
							</u-table>
						</view>
					</scroll-view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
// 脚本部分保持不变
import { ref, onMounted, onUnmounted } from "vue"
import { onReady, onLoad } from "@dcloudio/uni-app"
import mapVue from '../components/mapcomment.vue';
import { deviceInfoPageApi, lastdpbyIdApi, hisdpsApi } from "@/axios/pageApi/device"

// 页面参数
let name = ref("")
onLoad((e) => {
	name.value = e.name
})
let tableheight = ref('50')

// 数据状态
const isEnd = ref(true)
const minDate = ref('2024-01-01')
const maxDate = ref('')
let dateValue = ref('')
const calendarShow = ref(false)
const mode = ref('range')
const isMappage = ref(false)
const userDetails = ref({
	latitude: 39.822133,
	longitude: 108.7153
})
const current = ref(0)
const mothData = ref({})
const liveDate = ref({})
const tableData = ref([])
const selectMarker = ref({})
const pageSize = ref(10)
let dateRange = ref('')
let idArrStr = ref('')
const calendarValue = ref([])
const loading = ref(false)

// 表格列宽拖动相关变量
const columnWidths = ref([180, 150, 150, 130, 100]) // 初始列宽
const columnIndex = ref(-1) // 当前拖动的列索引
const startX = ref(0) // 拖动起始X坐标
const startWidth = ref(0) // 拖动起始宽度

// 页面加载
onReady(() => {
	getMothData()
	const dateObj = getDateRange()
	dateRange.value = `${dateObj.oneWeekAgo}-${dateObj.today}`
	calendarValue.value = [dateObj.oneWeekAgo, dateObj.today]
	getdeviceInfo(name.value)
	getTodayString()
})

// 页面挂载时添加触摸事件监听
onMounted(() => {
	document.addEventListener('touchmove', handleTouchMove, false)
	document.addEventListener('touchend', handleTouchEnd, false)
})

// 页面卸载时移除事件监听
onUnmounted(() => {
	document.removeEventListener('touchmove', handleTouchMove, false)
	document.removeEventListener('touchend', handleTouchEnd, false)
})

// 日期格式化
function formatDate(timestamp) {
	const date = new Date(timestamp);
	const year = date.getFullYear();
	const month = ('0' + (date.getMonth() + 1)).slice(-2);
	const day = ('0' + date.getDate()).slice(-2);
	const hours = ('0' + date.getHours()).slice(-2);
	const minutes = ('0' + date.getMinutes()).slice(-2);
	return `${year}-${month}-${day} ${hours}:${minutes}`;
}

// 获取今日日期
function getTodayString() {
	const today = new Date();
	const year = today.getFullYear();
	const month = today.getMonth() + 1;
	const date = today.getDate();
	maxDate.value = `${year}-${month}-${date}`;
}

// 日历确认
function confirm(e) {
	console.log(e, 'llll', e[0], e[e.length - 1]);

	dateRange.value = `${e[0]}-${e[e.length - 1]}`;
	calendarValue.value = [e[0], e[e.length - 1]];
	calendarShow.value = false;
	gethisdps();
}

// 获取日期范围
function getDateRange() {
	const today = new Date();
	const oneWeekAgo = new Date();
	oneWeekAgo.setDate(today.getDate() - 7);

	const formatDate = (date) => {
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0');
		const day = String(date.getDate()).padStart(2, '0');
		return `${year}-${month}-${day}`;
	};

	return {
		today: formatDate(today),
		oneWeekAgo: formatDate(oneWeekAgo)
	};
}

// 获取设备信息
async function getdeviceInfo(e) {
	try {
		const res = await deviceInfoPageApi(e);
		userDetails.value = res.data || {};
		selectMarker.value = { ...userDetails.value, iconPath: '/static/marker.png' };
		lastdpbyId(userDetails.value.imei);
	} catch (error) {
		console.error('获取设备信息失败:', error);
		uni.showToast({ title: '获取设备信息失败', icon: 'none' });
	}
}

// 获取实时数据
async function lastdpbyId(params) {
	if (!params) return;
	try {
		const res = await lastdpbyIdApi(params);
		const dpsdata = res.data.devs[0]?.dps || [];
		const idArr = [];
		dpsdata.forEach(item => {
			liveDate.value[item.title] = { value: item.value, unit: item.unit };
			idArr.push(item.id);
		});
		idArrStr.value = idArr.join(',');
		gethisdps();
	} catch (error) {
		console.error('获取实时数据失败:', error);
		uni.showToast({ title: '获取实时数据失败', icon: 'none' });
	}
}
function changeLastData() {
	current.value = 1
	gethisdps()
}
// 获取历史数据
async function gethisdps() {
	if (!userDetails.value.imei || !idArrStr.value) return;

	try {
		isEnd.value = true; // 显示加载状态
		const obj = {
			did: userDetails.value.imei,
			dsids: idArrStr.value,
			start: `${calendarValue.value[0]} 00:00:00`,
			end: `${calendarValue.value[1]} 23:59:59`
		};

		const res = await hisdpsApi(obj);
		const dpsdata = res.data.dss || [];

		const fieldsToCompare = ["FS_d_1", "FS_d_2", "FS_d_3", "FS_d_4", "FS_d_6"];
		const dedupedData = deduplicateTableData(transformDataForTable(dpsdata), fieldsToCompare);
		tableData.value = dedupedData.sort((a, b) => b.timestamp - a.timestamp);
		tableheight.value = tableData.value.length > 11 ? '500' : tableData.value.length ? ((tableData.value.length + 1) * 50 - 20).toString() : '100'
	} catch (error) {
		console.error('获取历史数据失败:', error);
		uni.showToast({ title: '获取历史数据失败', icon: 'none' });
	} finally {
		isEnd.value = false; // 隐藏加载状态
	}
}

// 数据去重
function deduplicateTableData(tableData, fields) {
	const seen = new Set();
	return tableData.filter(row => {
		const key = fields.map(field => row[field]).join('|');
		if (seen.has(key)) return false;
		seen.add(key);
		return true;
	});
}

// 数据转换
function transformDataForTable(data) {
	const groupedData = {};
	data.forEach(item => {
		const { id, name, title, dps } = item;
		dps.forEach(dp => {
			const { at, value } = dp;
			if (!groupedData[at]) {
				groupedData[at] = { timestamp: at, items: [] };
			}
			groupedData[at].items.push({ id, name, title, value });
		});
	});

	return Object.values(groupedData).map(group => {
		const row = { timestamp: group.timestamp };
		group.items.forEach(item => {
			row[item.name] = item.value;
		});
		return row;
	});
}

// 获取月度数据
function getMothData() {
	setTimeout(() => {
		mothData.value = {
			categories: ["2018", "2019", "2020", "2021", "2022", "2023"],
			series: [
				{ name: "目标值", data: [35, 36, 31, 33, 13, 34] },
				{ name: "完成量", data: [18, 27, 21, 24, 6, 28] }
			]
		};
	}, 500);
}

// 表格列宽拖动事件
function handleTouchStart(index) {
	columnIndex.value = index;
	startX.value = event.touches[0].clientX;
	startWidth.value = columnWidths.value[index];
	document.body.style.userSelect = 'none'; // 防止拖动时选中文本
}

function handleTouchMove(event) {
	if (columnIndex.value === -1) return;

	// 计算移动距离并更新列宽
	const moveX = event.touches[0].clientX - startX.value;
	const newWidth = Math.max(80, startWidth.value + moveX); // 最小宽度80px
	columnWidths.value[columnIndex.value] = newWidth;

	// 阻止事件冒泡和默认行为
	event.preventDefault();
	event.stopPropagation();
}

function handleTouchEnd() {
	if (columnIndex.value !== -1) {
		columnIndex.value = -1;
		document.body.style.userSelect = ''; // 恢复文本选择
	}
}
</script>

<style scoped lang="scss">
// 基础变量 - 浅蓝色主题
$primary-color: #4a90e2; // 主色调：浅蓝色
$primary-light: #e6f0fc; // 浅色调
$primary-dark: #3a80d2; // 深色调
$text-primary: #333333; // 主要文本
$text-secondary: #666666; // 次要文本
$text-tertiary: #999999; //  tertiary文本
$border-color: #e5e9f2; // 边框颜色
$bg-color: #f7f9fc; // 背景色
$card-bg: #ffffff; // 卡片背景

.details-page {
	background-color: $bg-color;
	min-height: 100vh;
}

/* 地图容器保持不变 */
.map-container {
	width: 100%;
	height: 200px;
	background-color: #aaa;
	overflow: hidden;

	>div {
		height: 100% !important;
	}
}

/* 内容容器 */
.content-wrapper {
	padding: 16rpx;
}

/* 卡片样式 */
.info-card {
	background-color: $card-bg;
	border-radius: 16rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.04);
	margin-bottom: 20rpx;
	overflow: hidden;
	transition: box-shadow 0.3s ease;

	&:hover {
		box-shadow: 0 5rpx 15rpx rgba(0, 0, 0, 0.07);
	}
}

.card-header {
	padding: 20rpx 24rpx;
	border-bottom: 1rpx solid $border-color;
	background-color: $primary-light;
}

.card-title {
	font-size: 30rpx;
	color: $primary-color;
	font-weight: 500;
}

/* 设备信息样式 */
.device-info {
	padding: 24rpx;
	position: relative;
}

.device-name {
	font-size: 32rpx;
	color: $text-primary;
	font-weight: 500;
	margin-bottom: 24rpx;
	padding-bottom: 16rpx;
	border-bottom: 1rpx dashed $border-color;
}

.info-grid {
	display: grid;
	grid-template-columns: 1fr 1fr;
	gap: 20rpx;
}

.info-item {
	display: flex;
	flex-direction: column;
	padding: 10rpx 0;
}

.info-label {
	font-size: 26rpx;
	color: $text-secondary;
	margin-bottom: 6rpx;
}

.info-value {
	font-size: 28rpx;
	color: $text-primary;
	word-break: break-all;
}

/* 设备状态 */
.device-status {
	position: absolute;
	top: 24rpx;
	right: 24rpx;
	padding: 6rpx 16rpx;
	border-radius: 20rpx;
	font-size: 24rpx;
	font-weight: 500;
}

.status-online {
	background-color: #e6f7f0;
	color: #00b42a;
}

.status-offline {
	background-color: #fef0f0;
	color: #f53f3f;
}

/* Tab切换样式 */
.tab-container {
	margin-bottom: 20rpx;
}

.tab-wrapper {
	display: flex;
	background-color: $card-bg;
	border-radius: 12rpx;
	overflow: hidden;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.04);
}

.tab-item {
	flex: 1;
	height: 88rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	position: relative;
	transition: all 0.3s;

	&:active {
		background-color: $primary-light;
	}
}

.tab-item.active {
	background-color: $primary-color;
}

.tab-text {
	font-size: 28rpx;
	color: $text-secondary;
}

.tab-item.active .tab-text {
	color: #fff;
	font-weight: 500;
}

/* 内容区域样式 */
.content-area {
	background-color: $card-bg;
	border-radius: 16rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.04);
	overflow: hidden;
}

/* 实时数据样式 */
.realtime-container {
	padding: 24rpx;
}

.data-cards {
	display: grid;
	grid-template-columns: 1fr 1fr;
	gap: 20rpx;
}

.data-card {
	background-color: $primary-light;
	border-radius: 12rpx;
	padding: 20rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	text-align: center;
	transition: all 0.3s ease;

	&:active {
		transform: translateY(2rpx);
		box-shadow: 0 2rpx 8rpx rgba(74, 144, 226, 0.2);
	}
}

.data-icon {
	font-size: 40rpx;
	margin-bottom: 15rpx;
	color: $primary-color;
}

.data-title {
	font-size: 26rpx;
	color: $text-secondary;
	margin-bottom: 12rpx;
}

.data-value {
	font-size: 32rpx;
	color: $primary-color;
	font-weight: 500;
}

/* 历史记录样式（修改部分） */
.history-container {
	min-height: 68vh;
}

.history-scroll {
	height: 68vh;
}

.date-picker {
	padding: 24rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	border-bottom: 1rpx solid $border-color;
	background-color: $primary-light;

	&:active {
		background-color: #dce8f8;
	}
}

.date-text {
	font-size: 28rpx;
	color: $primary-color;
}

.date-icon {
	font-size: 24rpx;
	color: $primary-color;
}

/* 表格样式（重点修改） */
.history-table {
	padding: 16rpx;
}

.draggable-table {
	position: relative;
	width: 100%;
	overflow-x: auto; // 允许水平滚动
}

.table-header {
	display: flex;
	background-color: $primary-color;
	border-radius: 8rpx 8rpx 0 0;
	overflow: hidden;
	min-width: 780px; // 确保表格可滚动
}

.table-col {
	flex-shrink: 0; // 禁止列收缩
	padding: 16rpx 12rpx;
	font-size: 26rpx;
	text-align: center;
	font-weight: 500;
}

.table-header .table-col {
	color: #fff;
	position: relative;
}

// 表体滚动容器
.table-body-scroll {
	max-height: 500px; // 固定表体高度，超出则滚动
}

.table-body {
	border: 1rpx solid $border-color;
	border-top: none;
	border-radius: 0 0 8rpx 8rpx;
	overflow: hidden;
	min-width: 880px; // 确保表格可滚动
}

.table-row {
	display: flex;
	border-bottom: 1rpx solid $border-color;
	transition: background-color 0.2s;

	&:last-child {
		border-bottom: none;
	}

	&:active {
		background-color: $primary-light;
	}
}

.row-odd {
	background-color: #f9fbfe;
}

.table-row .table-col {
	color: $text-primary;
	font-size: 26rpx;
	padding: 20rpx 16rpx;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}

/* 列宽拖动把手 */
.resize-handle {
	position: absolute;
	top: 0;
	right: 0;
	width: 6px;
	height: 100%;
	cursor: col-resize;
	background-color: transparent;
	transition: background-color 0.2s;

	&:active {
		background-color: rgba(74, 144, 226, 0.7);
	}
}

/* 空数据样式 */
.empty-data {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 200rpx;
	color: $text-tertiary;
	font-size: 28rpx;
}

/* 响应式调整 */
@media (max-width: 375px) {
	.info-grid {
		grid-template-columns: 1fr;
	}

	.data-cards {
		grid-template-columns: 1fr;
	}

	.table-col {
		min-width: 60px;
	}

	// 适配小屏幕的表体高度
	.table-body-scroll {
		max-height: 410px;
	}
}
</style>